//
//  YWGesturesViewController.m
//  GestureLock
//
//  Created by YR on 2017/6/5.
//  Copyright © 2017年 YR. All rights reserved.
//

#import "YWGesturesViewController.h"

#import "YWGesturesUnLockView.h"
#import "Masonry.h"

#define GesturesPassword @"gesturespassword"

@interface YWGesturesViewController ()<YWGesturesUnLockViewDelegate>

@property (nonatomic) UILabel *tipLabel;
@property (nonatomic) YWGesturesUnLockView *lockView;
@property (nonatomic) YWGesturesUnLockType gesturesUnlockType;

@property (nonatomic) NSString *firstPasswd;

@property (nonatomic) UILabel *validateTipLabel;
@property (nonatomic) NSInteger errorCount;

@end

@implementation YWGesturesViewController
#pragma mark - 类方法
+ (void)deleteGesturesPassword {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:GesturesPassword];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)addGesturesPassword:(NSString *)gesturesPassword {
    [[NSUserDefaults standardUserDefaults] setObject:gesturesPassword forKey:GesturesPassword];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString *)gesturesPassword {
    return [[NSUserDefaults standardUserDefaults] objectForKey:GesturesPassword];
}


- (instancetype)initWithLockType:(YWGesturesUnLockType)type {
    self = [super init];
    if (self) {
        self.view.backgroundColor = [UIColor whiteColor];
        _gesturesUnlockType = type;
        [self layout];
    }
    return self;
}

- (void)layout {
    if (_gesturesUnlockType == kYWGesturesUnLockTypeValid) {
        _errorCount = 5;
        
        [self.view addSubview:self.validateTipLabel];
        [_validateTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(50);
            make.height.mas_equalTo(60);
            make.left.right.equalTo(self.view);
            make.centerX.equalTo(self.view);
        }];
    } else {
        [self.view addSubview:self.tipLabel];
        [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(50);
            make.height.mas_equalTo(60);
            make.left.right.equalTo(self.view);
            make.centerX.equalTo(self.view);
        }];
    }
    [self.view addSubview:self.lockView];
    [_lockView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).with.offset(100);
    }];
}

- (void)createGesture:(NSString *)passwd {
    if (!_firstPasswd) {
        if (passwd.length < 4) {
            self.tipLabel.text = @"至少链接四个点，请重新绘制";
            return;
        }
        _firstPasswd = passwd;
        self.tipLabel.text = @"请再次绘制";
    } else {
        if ([_firstPasswd isEqualToString:passwd]) {
            [YWGesturesViewController addGesturesPassword:_firstPasswd];
            [self dismissViewControllerAnimated:YES completion:^{
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"手势密码设置成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"ok", nil];
                [alertView show];
            }];
        } else {
            self.tipLabel.text = @"与上一次绘制不一致，请重新绘制";
            [self shakeAnimationForView:self.tipLabel];
        }
    }
    
}

- (void)validate:(NSString *)passwd {
    if ([passwd isEqualToString:[YWGesturesViewController gesturesPassword]]) {
        [self dismissViewControllerAnimated:YES completion:^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"验证成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"ok", nil];
            [alertView show];
        }];
    } else {
        _errorCount --;
        if (_errorCount < 1) {
            [self dismissViewControllerAnimated:YES completion:^{
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"验证失败" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"ok", nil];
                [alertView show];
            }];
        } else {
            self.validateTipLabel.text = [NSString stringWithFormat:@"密码绘制失败，还可以输入%ld次",_errorCount];
            [self shakeAnimationForView:self.validateTipLabel];
        }
    }
}

//抖动动画
- (void)shakeAnimationForView:(UIView *)view
{
    CALayer *viewLayer = view.layer;
    CGPoint position = viewLayer.position;
    CGPoint left = CGPointMake(position.x - 10, position.y);
    CGPoint right = CGPointMake(position.x + 10, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFromValue:[NSValue valueWithCGPoint:left]];
    [animation setToValue:[NSValue valueWithCGPoint:right]];
    [animation setAutoreverses:YES]; // 平滑结束
    [animation setDuration:0.08];
    [animation setRepeatCount:3];
    
    [viewLayer addAnimation:animation forKey:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.lockView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - delegate
- (void)gesturesUnlockView:(YWGesturesUnLockView *)unlockView drawRectFinished:(NSMutableString *)gesturePassword {
    switch (_gesturesUnlockType) {
        case kYWGesturesUnLockTypeCreate:
        {
            [self createGesture:gesturePassword];
        }
            
            break;
        case kYWGesturesUnLockTypeValid: {
            [self validate:gesturePassword];
        }
        default:
            break;
    }
}

- (YWGesturesUnLockView *)lockView {
    if (!_lockView) {
        _lockView = [[YWGesturesUnLockView alloc] init];
        _lockView.delegate = self;
    }
    return _lockView;
}

- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] init];
        _tipLabel.text = @"请绘制手势密码";
        _tipLabel.textColor = [UIColor blackColor];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _tipLabel;
}

- (UILabel *)validateTipLabel {
    if (!_validateTipLabel) {
        _validateTipLabel = [[UILabel alloc] init];
        _validateTipLabel.text = @"请绘制手势密码";
        _validateTipLabel.textColor = [UIColor blackColor];
        _validateTipLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _validateTipLabel;
}



@end
